shanbay.chatting = (function() {

  var nav_meta = [ {
    id : "msg",
    type : "msg",
    title : "短信",
    url : function() {
      var url = shanbay.ntf.get_ntf_msg_url();
      if (!url) {
        url = "http://www.shanbay.com/17mail/inbox/";
      }
      return url;
    },
    list_selector : "#right-content:first table:first tr:gt(0)",
    user_selector : "td:eq(0)",
    title_selector : "td:eq(1)",
    link_selector : "td:eq(1) a:first"
  }, {
    id : "reply",
    type : "forum",
    title : "回复",
    url : function() {
      var url = shanbay.ntf.get_ntf_reply_url();
      if (!url) {
        url = "http://www.shanbay.com/forum/reply_to_me/";
      }
      return url;
    },
    list_selector : "#djangoForumThreadPosts .post",
    user_selector : ".djangoForumThreadPostDetail a:first",
    title_selector : ".djangoForumThreadPostDetail a:eq(1)",
    link_selector : ".djangoForumThreadPostDetail a:eq(1)"
  }, {
    id : "team",
    type : "forum",
    title : "小组",
    url : function() {
      if (!shanbay.user_info.in_team) {
        return null;
      } else {
        return shanbay.user_info.team_href;
      }
    },
    list_selector : ".team_detail:first > ul:last li",
    user_selector : ".thread_author a",
    title_selector : ".span6",
    link_selector : ".span6 a"
  }, {
    id : "misc",
    type : "forum",
    title : "水版",
    url : "http://www.shanbay.com/forum/misc/",
    list_selector : "#right-content:first table:first tr:gt(0)",
    user_selector : "td:eq(1)",
    title_selector : "td:eq(0)",
    link_selector : "td:eq(0) a:first"
  }, {
    id : "mythreads",
    type : "forum",
    title : "参与",
    url : "http://www.shanbay.com/forum/misc/",
    list_selector : "#mythreads:first > ul > li",
    user_selector : "null",
    title_selector : "a",
    link_selector : "a"
  } ];

  //抓取消息、主题列表
  this.retrieve_list = function(url, meta, $list_container) {
    $list_container.loading();

    if (!url) {
      if (typeof meta.url == "string") {
        url = meta.url;
      } else {
        url = meta.url();
      }
    }

    var $table = $("<table/>");
    var className = shanbay.generate_id("hover_list");

    $.get(url, function(data) {
      $(data).find(meta.list_selector).each(
          function() {
            var $this = $(this);
            var $tr = $("<tr/>").appendTo($table);

            //link
            $tr.data("url", $this.find(meta.link_selector).prop("href"));

            //author
            $("<td/>").append(
                $("<div/>").text($this.find(meta.user_selector).text()))
                .appendTo($tr);

            //title
            var $title = $("<div/>").append($this.find(meta.title_selector));
            $title.find("a").each(function() {
              var $span = $("<span/>").text($(this).text());
              $(this).replaceWith($span);
            });
            $("<td/>").append($("<div/>").append($title.children())).appendTo(
                $tr);

            $tr.hover(function() {
              $(this).toggleClass(className);
            }).click(function() {
              window.scrollTo(0, 0);
              var url = $(this).data("url");
              $chat_content.data("url", url);
              shanbay.chatting.retrieve_content[meta.type](url);
            });
          });

      $list_container.empty().append($table).loading(false);
    });

  };

  //抓取短信、帖子内容
  this.retrieve_content = {
    "msg" : function(url) {
      $chat_content_panel.loading();

      $.get(url, function(data) {
        var $data = $(data).find("#right-content:first");

        //build page
        var $header = $data.find(".message-headers:first");
        var sender = $header.find("p:first span:eq(1)").text();
        var date = $header.find("p:eq(2) span:eq(1)").text();
        var title = $header.find("p:eq(3) span:eq(1)").text();
        var $content = $data.find(".message");
        $content.find("p:last").remove();
        
        //[扇贝助手]新回复提醒
        if (title == "[扇贝助手]新回复提醒") {
          var post_link = $content.text().match(/链接：\[ ([^ ]+) \]/)[1];
          $content.append($("<button>查看原帖</button>").click(function() {
            $chat_content.data("url", post_link);
            shanbay.chatting.retrieve_content["forum"](post_link);
          }));
        }

        shanbay.chatting.reset_content_panel(url, sender, title);
        shanbay.chatting.wrap_msg(sender, date, $content);

        $chat_content_panel.loading(false);
      }, 'html');
    },

    "forum" : function(url) {
      $chat_content_panel.loading();

      $.get(url, function(data) {
        var $data = $(data).find("#right-content:first");

        var title = $data.find("#threadtitle:first").text();
        shanbay.chatting.reset_content_panel(url, null, title);

        //build page
        //msg
        $data.find("div.post").each(function() {
          $this = $(this);

          var $user = $this.find(".userinfo>.user:first");
          var user = $user.text();
          var real_id = shanbay.user.get_name_from_urls([$user.prop("href")])[0];

          var date = $.trim($this.find(".time:first").text().substring(5));
          var $content = $this.find(".post-content-todo:first");

          shanbay.chatting.wrap_msg([ user, real_id ], date, $content);
        });

        //pagination
        $data.find(".djangoForumPagination").each(
            function() {
              var $link = $(this).children("a");
              $link.data("page", $link.prop("href").match(/.*?page=(\d+)/)[1])
                  .prop("href", "javascript:void(0)").click(
                      function() {
                        var url = $chat_content.data("url") + "?page="
                            + $(this).data("page");
                        shanbay.chatting.retrieve_content["forum"](url);
                      });
              $link.appendTo($pagination).after($("<span> </span>"));
            });

        //reply_to_user
        var title_selector = "." + shanbay.generate_id("chat_msg_title");
        var user_selector = "." + shanbay.generate_id("chat_msg_author");

        $chat_content_panel.find(title_selector).each(
            function() {
              var $menu = $("<div/>").prop("class",
                  shanbay.generate_id("chat_msg_menu")).appendTo($(this));

              var real_id = $(this).find(user_selector).data("user");

              $("<a/>").text("@Ta").prop("href", "javascript:void(0)").appendTo(
                  $menu).click(function() {

                var text = $textarea.val();
                if (text)
                  text += "\n";

                text += "@" + decodeURIComponent(real_id) + " ";
                $textarea.val(text);

                var last = $textarea.val().length;
                var ta = $textarea.get(0);
                ta.setSelectionRange(last, last);
                ta.focus();

                //i've wasted a lot of time here!
                $chat_content.get(0).scrollTop = 99999999;
              });

              $("<a/>").text("短信").appendTo($menu).prop({
                href : "http://www.shanbay.com/17mail/compose/" + real_id,
                target : "_blank"
              })
            });

        $chat_content_panel.loading(false);
      }, 'html');
    }
  };

  //闲聊面板
  //chat_div
  //chat_list_panel                chat_content_panel
  //  chat_nav                       chat_cotent_title
  //    nav1, nav2, nav3..           chat_content
  //  chat_list                        chat_msgs : msg1 <br/> msg2 <br/> msg3..
  //    list1, list2, list3..          chat_reply : input <br/> button(提交) span(成功)
  var $chat_div = $("<div/>").prop("id", shanbay.generate_id("chat_div"));

  //左侧消息列表
  var $chat_listcontainer = $("<div/>").prop("class",
      shanbay.generate_id("chat_list_panel")).appendTo($chat_div);

  var $chat_nav = $("<div/>").prop("class", shanbay.generate_id("chat_nav"))
      .appendTo($chat_listcontainer);
  var $chat_list = $("<div/>").prop("class", shanbay.generate_id("chat_list"))
      .appendTo($chat_listcontainer);

  for ( var i in nav_meta) {
    var meta = nav_meta[i];
    $("<span/>").prop("id", meta.id).text(meta.title).data("id", i).appendTo($chat_nav);
    $("<div/>").prop("class", shanbay.generate_id("chat_list")).appendTo(
        $chat_list);
  }

  //右侧消息面板
  var $chat_content_panel = $("<div/>").prop("class",
      shanbay.generate_id("chat_content_panel")).appendTo($chat_div);

  var $chat_content_title = $("<div/>").prop("class",
      shanbay.generate_id("chat_content_title")).appendTo($chat_content_panel);
  var $chat_content = $("<div/>").prop("class",
      shanbay.generate_id("chat_content")).appendTo($chat_content_panel);

  var $chat_msgs = $("<div/>").prop("class", shanbay.generate_id("chat_msgs"))
      .appendTo($chat_content);

  var $pagination = $("<div/>").prop("class",
      shanbay.generate_id("chat_pagination")).appendTo($chat_content);

  var $chat_reply = $("<div/>")
      .prop("class", shanbay.generate_id("chat_reply")).appendTo($chat_content);
  var $textarea = $("<textarea/>")
      .prop("id", shanbay.generate_id("chat_input")).appendTo($chat_reply);
  $("<br/>").appendTo($chat_reply);
  var $submit = $("<button>回复</button>").appendTo($chat_reply);
  var $tip = $("<span/>").appendTo($chat_reply);

  this.reset_content_panel = function(url, user, title) {
    //title
    origin_link = ($("<a/>").text("[打开原帖]")
                            .prop({
                              target: "_blank",
                              href: url,
                            }).css({
                              color: "white",
                              float: "right",
                            }));
    ($chat_content_title.empty()
                        .append(origin_link)
                        .append($("<b/>").text(title)));

    //content
    $chat_content.show();
    $chat_content.get(0).scrollTop = 0;
    $chat_msgs.empty();
    $pagination.empty();

    //reply
    $chat_content.data({
      type : url.indexOf("mail") != -1 ? "mail" : "forum",
      user : user,
      title : title
    });

    $textarea.val("");
    $tip.empty();
  };

  this.wrap_msg = function(user, date, $content) {
    var real_id;
    if (typeof user != "string") {
      real_id = user[1];
      user = user[0];
    } else {
      real_id = user;
    }

    var $title = $("<div/>").addClass(shanbay.generate_id("chat_msg_title"))
        .append($("<span/>").text("posted " + date + " by "));
    $title.append($("<span/>").prop("class",
        shanbay.generate_id("chat_msg_author")).text(user)
        .data("user", real_id));

    $chat_msgs.append($title).append(
        $content.prop("class", shanbay.generate_id("chat_msg_content")));
  };

  //事件
  var current_nav_class = shanbay.generate_id("current_nav");
  var $current_nav = $chat_nav.find("span:first").addClass(current_nav_class);
  var $current_list = $chat_list.find("div:first");

  $chat_nav.find("span").hover(function() {
    $(this).toggleClass(shanbay.generate_id("hover_nav"));
  }).click(function() {
    var id = $(this).data("id");
    $current_nav.removeClass(current_nav_class);
    $current_nav = $(this).addClass(current_nav_class);
    $current_list.hide();
    $current_list = $chat_list.children("div:eq(" + id + ")").show();

    var meta = nav_meta[id];
    shanbay.chatting.retrieve_list(null, meta, $current_list);
  });

  //提交
  $submit.click(function() {
    $tip.text("正在提交...");
    var title = $chat_content.data("title");
    var content = $textarea.val();

    if ($chat_content.data("type") == "mail") {
      title = title.indexOf("回复:") == 0 ? title : "回复: " + title;
      shanbay.mail.mail_to($chat_content.data("user"), title, content,
          function() {
            $tip.text("成功");
            $textarea.val("");
          });

    } else {
      shanbay.forum.reply_to($chat_content.data("url"), title, content,
          function() {
            $tip.text("成功");
            $textarea.val("");
          });
    }
  });

  this.enhance_chatting = function() {
    $chat_div.appendTo($("body"));
  };

  this.show = function(spanid) {
    $chat_div.toggle();
    if (spanid) {
      $chat_div.find("#" + spanid).click();
    }
  };

  return this;
})();

$(function() {
  shanbay.chatting.enhance_chatting();
});
